import {_decorator, Prefab, Node, resources, instantiate, Vec3, Quat} from 'cc';
import Singleton from "db://assets/scripts/common/Singleton";

const {ccclass, property} = _decorator;

/**
 * 预制体管理器
 */
@ccclass('PrefabManager')
export class PrefabManager extends Singleton {

    private prefabs: Map<string, Prefab> = new Map();

    init() {
        // 加载预制体
        this.loadAllPrefabs(["prefabs"]);
    }

    //预加载所有预制体
    loadAllPrefabs(prefabPaths: string[]) {
        for (const path of prefabPaths) {
            resources.loadDir(path, Prefab, (err, prefabs) => {
                if (err) {
                    console.error("loadAllPrefabs error ", err.message);
                    return;
                }
                for (const prefab of prefabs) {
                    console.info("load prefab: ", prefab.name);
                    this.prefabs.set(prefab.name, prefab);
                }
            });
        }
    }

    // 根据名称实例化预制体
    static instantiate(prefabName: string, parent?: Node, position?: Vec3, rotation?: Quat): Node | null {
        let prefabManager = this.getInstance();
        const prefab = prefabManager.prefabs.get(prefabName);
        if (prefab) {
            const instance = instantiate(prefab);
            if (parent) {
                instance.parent = parent;
            }
            if (position) {
                instance.setPosition(position);
            }
            if (rotation) {
                instance.setRotation(rotation);
            }
            return instance;
        } else {
            console.warn(`Prefab not found: ${prefabName}`);
            return null;
        }
    }
}


